//https://leetcode.cn/problems/permutations-ii/
package codeRandomThoughts.Test47全排列II;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        boolean[] usedV = new boolean[nums.length];
        backtracking(nums, usedV);
        return result;
    }

    /**
     * usedH代表横向有没有用过这个数字
     * usedV代表纵向有没有用过这个位置上的数字
     *
     * @param nums
     * @param usedV
     */
    public void backtracking(int[] nums, boolean[] usedV) {
        //终止条件
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }

        //单层搜索逻辑
        boolean[] usedH = new boolean[21];
        for (int i = 0; i < nums.length; i++) {
            if (!usedV[i] && !usedH[nums[i]+10]) {
                usedH[nums[i]+10] = true;
                path.add(nums[i]);
                usedV[i] = true;
                backtracking(nums, usedV);
                path.remove(path.size() - 1);
                usedV[i] = false;
            }
        }

    }
}
